<!--
 * @Author: yan_hai_dong 891236760@qq.com
 * @Date: 2022-08-02 10:31:32
 * @LastEditors: yan_hai_dong 891236760@qq.com
 * @LastEditTime: 2022-08-02 16:42:00
 * @FilePath: \app\src\views\el\css\snowflake\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <canvas ref="MyCanvas"></canvas>
  </div>
</template>

<script>
import InkImg from "./src/ink.jpg";
import BgImg from "./src/ft.png";
export default {
  name: "snowflake",
  data() {
    return {};
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let canvasEle = this.$refs.MyCanvas;
      const WIDTH = 4096;
      const HEIGHT = 4096;
      const width = 512;
      const height = 512;
      canvasEle.width = width;
      canvasEle.height = height;
      const ctx = canvasEle.getContext("2d");
      const bg = new Image(WIDTH, HEIGHT);
      const ft = new Image(width, height);
      bg.crossOrigin = "anonymous";
      ft.crossOrigin = "anonymous";
      bg.src = InkImg;
      ft.src = BgImg;
      const setPosition = (x, y) => {
        if (!ctx) return;
        ctx.save();// 保存当前状态
        ctx.drawImage( // 绘制源图片
          bg,
          x * width,
          HEIGHT - height - y * height,
          width,
          height,
          0,
          0,
          width,
          height
        );

        const imageData = ctx.getImageData(0, 0, width, height);// 获取图片数据
        const data = imageData.data;
        console.log(data)
        if (data) {
          for (var i = 0; i < data.length; i += 4) {
            let r = data[i];
            let g = data[i + 1];
            let b = data[i + 2];
            // 将高亮位置设置成透明通道
            if ([r, g, b].every((v) => v < 256 && v > 240)) {
              data[i + 3] = 0;
            }
          }
          ctx?.putImageData(imageData, 0, 0);// 绘制新的图片数据
        }
        ctx.globalCompositeOperation = "source-in"; // 设置画布重叠绘制方式
        ctx.drawImage(ft, 0, 0);// 绘制目标图片
        ctx.restore(); // 恢复之前保存的状态
        // 遍历图源位置信息
        if (x === 7) {
          if (y === 7) y = 0;
          else y++;
          x = 0;
        } else x++;

        // 绘制完成
        if (x === 0 && y === 0) return;

        setTimeout(() => {
          setPosition(x, y);
        }, 100);
      };
      bg.onload = () => {
        setPosition(0, 0);
      };
    },
  },
};
</script>

<style lang="less" scoped>
</style>